package com.gonsin.gview.common.auth.session;

import com.gonsin.gview.common.auth.JwtConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class JwtSessionFilterConfig {

    @Value("#{'${filterUrls:*}'.split(',')}")
    private String[] filterUrls;

    @Autowired private JwtConfig jwtConfig;

    @Bean
    @ConditionalOnMissingBean(FilterRegistrationBean.class)
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();

//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration config = new CorsConfiguration();
//        config.setAllowCredentials(true);
//        config.addAllowedOrigin("*");
//        //config.setAllowedOriginPatterns(Collections.singletonList("*"));
//        config.addAllowedHeader("x-requested-with,content-type,requesttype");
//        config.addAllowedMethod("*");
//        source.registerCorsConfiguration("/api/**", config);

        registrationBean.setFilter(new JwtSessionRequestFilter(jwtConfig.getJwtSecret())); // 自己的filter
        List<String> urlPatterns = new ArrayList<>();
        for(String url : filterUrls){
            urlPatterns.add(url);
        }
        registrationBean.setUrlPatterns(urlPatterns);
        return registrationBean;
    }

}
